package org.qiyu.live.msg.provider.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.config.annotation.DubboReference;;
import org.qiyu.live.im.dto.ImMsgBody;
import org.qiyu.live.msg.dto.MessageDTO;
import org.qiyu.live.msg.provider.consumer.ImMsgConsumer;
import org.qiyu.live.msg.provider.handler.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import qiyu.live.im.router.interfaces.IMRouterRpc;
import qiyu.live.living.dto.req.LivingRoomReqDTO;
import qiyu.live.living.interfaces.ILivingRoomRpc;

import java.util.ArrayList;
import java.util.List;

import static org.qiyu.live.msg.enums.ImBiZiCode.QIYU_LIVING_ROOM_BIZ_CODE;

/**
 * Created with IntelliJ IDEA.
 * Description: 这里进行具体的业务处理之后,远程调用Router服务,将消息给到router层
 * User: sfx
 * Date: 2023-10-18
 * Time: 20:06
 */
@Component
public class SingleMessageHandler implements MessageHandler {

    @DubboReference
    private IMRouterRpc imRouterRpc;

    @DubboReference
    private ILivingRoomRpc livingRoomRpc;


    @Override
    public void onMsgReceive(ImMsgBody imMsgBody) {
        int biZiCode = imMsgBody.getBiZiCode();
        // 这里是直播间发送群聊消息
        // 我们这里要做的就是把要推送的所有ImMsgBody准备好放到一个List集合,交给router层进行转发到具体的im-core-server
        // 机器上
        if(QIYU_LIVING_ROOM_BIZ_CODE.getCode() == biZiCode) {
            // 这里进行直播间的业务处理
            // 1. 查询到所有的UserId
            MessageDTO messageDTO = JSON.parseObject(imMsgBody.getData(), MessageDTO.class);
            LivingRoomReqDTO livingRoomReqDTO = new LivingRoomReqDTO();
            livingRoomReqDTO.setRoomId(messageDTO.getRoomId());
            livingRoomReqDTO.setAppId(messageDTO.getAppId());
            List<Long> userIds = livingRoomRpc.queryUserIdsByRoomId(livingRoomReqDTO);
            // 2. 为每一个userId构建好ImMsgBody,发送出去
            List<ImMsgBody> imMsgBodies = new ArrayList<>();
            userIds.forEach(userId -> {
                ImMsgBody respMsg = new ImMsgBody();
                respMsg.setUserId(userId);
                respMsg.setAppId(messageDTO.getAppId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userId", userId);
                jsonObject.put("content", messageDTO.getContent());
                respMsg.setData(jsonObject.toJSONString());
                imMsgBodies.add(respMsg);
            });
            imRouterRpc.batchSendMsg(imMsgBodies);
        }
    }
}